import io from 'socket.io-client'
import Store from '../../store'
import {SocketActionTypes, SET_SERVER_DATE} from '../../store/socket/types'

class SocketClient {

  /**
   * socket对象
   */
  readonly socket: SocketIOClient.Socket

  /**
   * 是否连接成功
   * @param uri
   * @param opts
   */
  isConnect: boolean = false

  /**
   * 构造函数
   * @param uri 默认为window.location
   * @param opts https://github.com/socketio/socket.io-client/blob/HEAD/docs/API.md#new-managerurl-options
   */
  constructor(uri: string, opts?: SocketIOClient.ConnectOpts) {
  this.socket = io(uri, opts);

  this.connect = this.connect.bind(this)
  this.disconnect = this.disconnect.bind(this)
  this.res = this.res.bind(this)
  this.date = this.date.bind(this)

  this.socket.on('connect', this.connect)
  this.socket.on('disconnect', this.disconnect)
  this.socket.on('res', this.res)
  this.socket.on('date', this.date)
}

/**
 * 连接成功的回调
 */
private connect() {
  this.isConnect = true
  console.log('connect')

  console.log('id = ', this.socket.id)

  setInterval(() => {
    this.socket.emit('chat', new Date().getSeconds());
  }, 2000);

  setTimeout(() => {
    this.socket.emit('close', new Date().getSeconds());
    // this.socket.close()
  }, 10000);
}

/**
 * 断开连接的回调
 */
private disconnect() {
  this.isConnect = false
  console.log('disconnect')
}

private res(msg: string) {
  console.log('res = ', msg)
}

private date(date: any) {
  console.log('date = ', date)
  Store.dispatch<SocketActionTypes>({
    type: SET_SERVER_DATE,
    value: date
  })
}
}

export default SocketClient
